using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace WebApplication
{
	/// <summary>
	/// Summary description for BuyNewTrain.
	/// </summary>
	public partial class BuyExistingTrain : System.Web.UI.Page
	{
		private	bool	_bBuyer;
		private	bool	_bSeller;
		private	string	_sBuyingPlayer;
		private	string	_sSellingPlayer;
		private	string	_sBuyingCompany;
		private	string	_sSellingCompany;
		private	string	_sTrain;
	
		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{    

		}
		#endregion

		protected void Page_Load(object sender, System.EventArgs e)
		{
			Game	game		= Global.getGame (this);;
			string	sPlayer		= Session["PlayerName"].ToString();
			bool	bPriority	= sPlayer == game.ExistingTrainPriorityPlayerName;
			
			ErrorMsg.Text = "";
			
			SetTitle(sPlayer);
			PriorityCheckBox.Text = sPlayer;
			
			PriorityCheckBox.Checked = bPriority;

			FillTableWithInfo();
			
			if (game.ExistingTrainSalePending)
			{
				Status.Text = "Enter the price you wish to pay and select the train to purchase";
				
				Accept.Visible	= false;
				Reject.Visible	= false;
				
				Price.Enabled	= true;
				_bBuyer			= true;	// force so button click takes
			}
			else if (game.ExistingTrainPurchaseSale)
			{
				int		nAmount		= game.ExistingTrainPurchasePrice;
				bool	bBidEntered	= nAmount > 0;
				
				_sTrain				= game.ExistingTrainToBuy;
				_sBuyingPlayer		= game.ExistingTrainBuyer.Name;
				_sSellingPlayer		= game.ExistingTrainSeller.Name;
				_sBuyingCompany		= game.ExistingTrainBuyingCompany.Name;
				_sSellingCompany	= game.ExistingTrainSellingCompany.Name;
				_bBuyer				= sPlayer == _sBuyingPlayer;
				_bSeller			= sPlayer == _sSellingPlayer;

				Back.Visible = false;
				
				if (_bBuyer)			// I am buying
				{
					if (nAmount != 0)	// no bid
						nAmount	= game.ExistingTrainPurchasePrice;
				
					if (!IsPostBack)
						Price.Text	= nAmount.ToString();
				
					if (!game.ExistingTrainPurchased)	// offer not accepted
					{
						if (_bBuyer && !_bSeller)		// not buying from myself
						{
							Status.Text = "Attempting to purchase a " + _sTrain + " train from " + _sSellingCompany + " for $" + game.ExistingTrainPurchasePrice;
				
							Accept.Visible	= false;
							Reject.Visible	= false;
					
							Price.Enabled	= !bBidEntered;
						}
						else
						{
							Status.Text = _sBuyingCompany + " wishes to buy a " + _sTrain + " train from " + _sSellingCompany + " for $" + nAmount;
			
							Accept.Text = "Accept";
							Reject.Text	= "Reject";

							Accept.Enabled = bBidEntered;
							Reject.Enabled = bBidEntered;
							Price.Enabled  = !bBidEntered;
						}
					}
					else
					{
						if (nAmount > 0)				// offer accepted ?
							Status.Text = "You bought a " + _sTrain + " train from "  + _sSellingCompany + " for $" + game.ExistingTrainPurchasePrice;
						else
							Status.Text = "Your offer to buy a "  + _sTrain + " train from " + _sSellingCompany + " was rejected";
				
						Accept.Visible	= false;
						Reject.Text		= "Done";
						Price.Enabled	= false;
					}
				}
				else if (_bSeller)		// I am selling
				{
					Price.Text	= nAmount.ToString();

					if (!game.ExistingTrainPurchased)	// offer not accepted
					{
						Status.Text = _sBuyingCompany + " wishes to buy a " + _sTrain + " train from " + _sSellingCompany + " for $" + nAmount;
			
						Accept.Text = "Accept";
						Reject.Text = "Reject";

						Accept.Enabled = bBidEntered;
						Reject.Enabled = bBidEntered;
					}
					else
					{
						if (nAmount > 0)				// offer accepted ?
							Status.Text = _sSellingCompany + " sold a " + _sTrain + " train to " + _sBuyingCompany + " for $" + nAmount;
						else
							Status.Text = _sSellingCompany + " rejected the offer to sell a " + _sTrain + " train to " + _sBuyingCompany;
			
						Accept.Enabled = false;
						Reject.Enabled = false;
					}
				
					Price.Enabled = false;
				}
				else					// I am viewing
				{
					Price.Text	= nAmount.ToString();

					if (!game.ExistingTrainPurchased)	// offer not accepted
						Status.Text = _sBuyingCompany + " is attempting to buy a " + _sTrain + " train from " + _sSellingCompany + " for $" + nAmount;
					else if (nAmount > 0)
						Status.Text = _sBuyingCompany + " bought the " + _sTrain + " train from " + _sSellingCompany + " for $" + nAmount;
					else
						Status.Text = _sBuyingCompany + "'s offer to buy a " + _sTrain + " train from " + _sSellingCompany + " was rejected";

					Accept.Visible	= false;
					Reject.Visible	= false;
					Price.Enabled	= false;
				}
			}
			else
			{
				Response.Redirect("OperatingRound2.aspx");
			}
		}

		private void SetTitle (string sNewTitle)
		{
			HtmlGenericControl title = this.FindControl ("Title") as HtmlGenericControl;

			if (title != null)
				title.InnerText = sNewTitle;
		}

		private void FillTableWithInfo()
		{
			int 			nRow = 0;
			Game			game = Global.getGame (this);;
			string			sPlayer = Session["PlayerName"].ToString ();
			Button			button;
			TableRow		row;
			TableCell		cell;
			PublicCompany	company;

			company = game.CurrentlyOperatingCompany;
			CompanyMoney.Text = company.Name + " has $" + company.Cash;

			foreach (Player player in game.Players)
			{
				foreach (Share share in player.Shares)
				{
					if (share.President)	// owns this company
					{
						nRow++;
						row = new TableRow();
						
						company = share.PublicCompany;
						
						// add player
						cell = new TableCell();
						cell.Text = player.Name;
						row.Cells.Add (cell);
						
						// add company
						cell = new TableCell();
						cell.Text = company.Name;
						row.Cells.Add (cell);
						
						// add company cash
						cell = new TableCell();
						cell.Text = company.Cash.ToString();
						row.Cells.Add (cell);

                        // add company loans
                        cell = new TableCell();
                        cell.Text = company.Loans.ToString();
                        row.Cells.Add(cell);

                        // add company trains
						cell = new TableCell();

						foreach (Train train in company.Trains)
						{
							button = new Button();
							button.Text = train.Name;
							button.Click += new System.EventHandler(this.BuyTrain);
                            
                            if (game.CollusionAllowed)
                                button.Enabled = company.Name != game.CurrentlyOperatingCompany.Name && game.ExistingTrainPurchasePrice == 0;
                            else
                                button.Enabled = sPlayer == player.Name && company.Name != game.CurrentlyOperatingCompany.Name && game.ExistingTrainPurchasePrice == 0;
							
                            button.CommandName = train.Name;		// train buying
							button.CommandArgument = company.Name;	// company buying from
							cell.Controls.Add(button);
						}
						
						row.Cells.Add (cell);
						TrainTable.Rows.AddAt(nRow, row);
					}
				}
			}
		}
		
		private void BuyTrain(object sender, System.EventArgs e)
		{
			Game	game	= Global.getGame (this);;
			Button	button	= (Button) sender;

			if (_bBuyer)
			{
//                int nPrice = int.Parse(Price.Text);

                int nPrice = -1;                    
                bool bPrice = int.TryParse(Price.Text, out nPrice);
                
                if (!bPrice)
                {
                    return;
                }

				if (nPrice > 0)
				{
					if (game.CurrentlyOperatingCompany.Cash >= nPrice)
					{
                        bool            bIsCGR          = false;
                        bool			bContinueSale	= true;
						string          sTrain          = button.CommandName;
                        PublicCompany	buyingCompany	= game.CurrentlyOperatingCompany;
						PublicCompany	sellingCompany	= game.PublicCompanies[button.CommandArgument];

                        bIsCGR = buyingCompany.Name == "CGR" || sellingCompany.Name == "CGR";

                        if (bIsCGR)
						{
                            if (buyingCompany.Name == "CGR" && !game.IsPermanantTrain(sTrain))
                            {
                                ErrorMsg.Text = "The CGR can only buy permanant trains.";
                                bContinueSale = false;
                            }
                            else
                            {
                                int nTrainPrice = sellingCompany.GetTrainToSell(sTrain).Cost;

                                // CGR can only buy or sell trains at face value
                                if (nPrice != nTrainPrice)
                                {
                                    ErrorMsg.Text = "The CGR can only buy or sell trains at face value.  The price must be $" + nTrainPrice.ToString();
                                    bContinueSale = false;
                                }
                            }
						}
						
						if (bContinueSale)
						{
							game.ResetExistingTrainSaleInfo();
							game.ExistingTrainPurchaseSale = true;
							game.ExistingTrainToBuy = sTrain;
							game.ExistingTrainBuyingCompany = buyingCompany;
							game.ExistingTrainSellingCompany = sellingCompany;
							game.ExistingTrainPurchasePrice = nPrice;
							game.ExistingTrainBuyer = buyingCompany.Owner;
							game.ExistingTrainSeller = sellingCompany.Owner;
							game.ExistingTrainPriorityPlayerName = sellingCompany.Owner.Name;
					
							PriorityCheckBox.Checked = false;
						
							Response.Redirect("BuyExistingTrain.aspx");
						}
					}
					else
					{
						ErrorMsg.Text = game.CurrentlyOperatingCompany.Name + " doesn't have enough cash.  It only have $" + game.CurrentlyOperatingCompany.Cash.ToString();
					}
				}
				else
				{
					ErrorMsg.Text = "No price entered.  Enter a price > $1";
				}
			}
		}

		protected void Accept_Click(object sender, System.EventArgs e)
		{
			Game	game	= Global.getGame (this);;

			if (_bBuyer)
			{
                int nBid = -1;
                bool bBid = int.TryParse(Price.Text, out nBid);

                if (!bBid)
                {
                    return;
                }

				if (nBid > 0)
				{
					if (game.CurrentlyOperatingCompany.Cash >= nBid)
					{
						game.ExistingTrainPurchasePrice = nBid;
						
						if (_bBuyer && !_bSeller)	// buying from another player
						{
							game.ExistingTrainPriorityPlayerName = _sSellingPlayer;
					
							PriorityCheckBox.Checked = false;
						}
						else						// buying from myself
						{
							string	sMsg;
							string	sErrorMsg;

							sMsg = _sBuyingCompany + " bought a " + _sTrain + " train from " + _sSellingCompany + " for $" + game.ExistingTrainPurchasePrice;
								
							game.History.Add (sMsg);

							// transfer the train and money
							game.ExistingTrainBuyingCompany.BuyExistingTrain(game.ExistingTrainSellingCompany, game.ExistingTrainToBuy, game.ExistingTrainPurchasePrice, out sErrorMsg);
							
							game.ExistingTrainPriorityPlayerName = _sBuyingPlayer;
							game.ExistingTrainPurchased = true;
				
							PriorityCheckBox.Checked = false;

							Response.Redirect("BuyExistingTrain.aspx");
						}
					}
					else
					{
						ErrorMsg.Text = _sBuyingCompany + " doesn't have enough cash.  It only has $" + game.CurrentlyOperatingCompany.Cash.ToString();
					}
				}
			}
			else if (_bSeller)
			{
				string	sMsg;
				string	sErrorMsg;

				sMsg = _sBuyingCompany + " bought a " + _sTrain + " train from " + _sSellingCompany + " for $" + game.ExistingTrainPurchasePrice;
								
				game.History.Add (sMsg);

				// transfer the train and money
				game.ExistingTrainBuyingCompany.BuyExistingTrain(game.ExistingTrainSellingCompany, game.ExistingTrainToBuy, game.ExistingTrainPurchasePrice, out sErrorMsg);

				game.ExistingTrainPriorityPlayerName = _sBuyingPlayer;
				game.ExistingTrainPurchased = true;
				
				PriorityCheckBox.Checked = false;

				Response.Redirect("BuyExistingTrain.aspx");
			}
		}
		
        protected void Reject_Click(object sender, System.EventArgs e)
		{
			Game	game	= Global.getGame (this);;
			
			if (_bBuyer)
			{
				game.ResetExistingTrainSaleInfo();
				
				Response.Redirect("BuyTrain.aspx");
			}
			else if (_bSeller)
			{
				game.ExistingTrainPurchasePrice = 0;	// tell him rejected
				game.ExistingTrainPriorityPlayerName = _sBuyingPlayer;
				game.ExistingTrainPurchased = true;
				
				PriorityCheckBox.Checked = false;

				Response.Redirect("BuyExistingTrain.aspx");
			}
		}

		protected void Back_Click(object sender, System.EventArgs e)
		{
			Response.Redirect("BuyTrain.aspx");
		}
	}
}
